package com.woniu.woniu_bx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.woniu_bx.dto.GoodsList;
import com.woniu.woniu_bx.pojo.Goods;
import com.woniu.woniu_bx.pojo.GoodsCategory;
import com.woniu.woniu_bx.pojo.PageBean;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.service.GoodsCategoryService;
import com.woniu.woniu_bx.service.GoodsCommentService;
import com.woniu.woniu_bx.service.GoodsService;
import com.woniu.woniu_bx.vo.GoodsSortVo;
import com.woniu.woniu_bx.vo.GoodsVo;
import com.woniu.woniu_bx.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Auther: Ayang
 * @Date: 2022/8/29 11:27
 * @Description: 商品管理
 */
@Slf4j
@RestController
@RequestMapping("")
@Validated
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;

    @Autowired
    private GoodsCommentService goodsCommentService;

    //多条件分页查询
    @PostMapping("/admin/goods/list")
    @PreAuthorize("hasAnyAuthority('goods:show')")
    public ResponseEntity<PageBean<Goods>> list(@RequestBody GoodsVo goodsVo) {
        log.debug("goodsVo : {}", goodsVo);

        // 每页展示条数，暂定 10
        Integer pageSize = 10;

        Goods goods = goodsVo.getGoods();
        Integer pageNum = goodsVo.getPageNum() == null ? 1 : goodsVo.getPageNum();
        PageBean<Goods> pageBean = goodsService.getByPage(goods, pageNum, pageSize);
        return ResponseEntity.SUCCESS("获取列表成功", pageBean);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 新增商品
     * @Date 16:35 2022/8/29
     * @Author 魏才林
     * @Param [goods]
     **/
    @PostMapping("/goods/add")
    public ResponseEntity add(@RequestBody Goods goods) {
        //TODO 数据校验，新增时除id、status、saleNum这些数据外都必须有值
        log.debug("接收到的参数：{}",goods);
        goodsService.add(goods);

        return ResponseEntity.SUCCESS("新增成功", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 更新陪玩商品信息（包括商品图片）
     * @Date 11.13 2022/8/30
     * @Author 魏才林
     * @Param [goods]
     **/
    @PostMapping("/goods/update")
    public ResponseEntity update(@RequestBody @NotNull Goods goods) {
        log.debug("接收到的参数：{}",goods);
        // TODO 后面可以约束下前端这边需不需要提前把goodsId也写好，这里就统一按照没有写好来处理，统一赋值，
        //  避免后台数据库出错
        goods.getGoodsImgs().forEach(i -> {
            i.setRelationalId(goods.getId());
        });
        goodsService.update(goods);
        return ResponseEntity.SUCCESS("修改成功", null);
    }

    /**
     * 逻辑删除商品
     * status：0代表未删除，1代表删除
     *
     * @param id 商品id
     * @return 返回操作结果，200 -> 删除成功，500 -> 操作失败
     * @throws Exception 数据库异常时，抛出该异常
     */
    @RequestMapping("/goods/delete")
    public ResponseEntity delete(@NotNull @Min(1) Integer id) {
        goodsService.delete(id);

        return ResponseEntity.SUCCESS("删除成功", null);
    }

    /**
     * 修改商品状态
     *
     * @param id
     * @param status
     * @return
     */
    @GetMapping("/admin/goods/updateStatus")
    @PreAuthorize("hasAnyAuthority('goods:updown')")
    public ResponseEntity delete(@NotNull Integer id, @NotNull String status) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setStatus(status);
        goodsService.updateByCondition(goods);
        return ResponseEntity.SUCCESS("操作成功", null);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 获得陪玩的所有未被删除的商品
     * @Date 10.43 2022/8/30
     * @Author 魏才林
     * @Param [userId]
     **/
    @GetMapping("/goods/getPwNoDelGoods")
    public ResponseEntity getPwNoDelGoods(@RequestBody GoodsVo goodsVo) {
        //分页数，暂定10
        Integer pageSize = 10;

        PageBean<Goods> goodsPageBean = goodsService.getAllGoodsNoDelByUserId(goodsVo.getUserId(), goodsVo.getPageNum(), pageSize);
        return ResponseEntity.SUCCESS("获取陪玩商品列表成功（未被逻辑删除的）", goodsPageBean);
    }

    /**
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Description 获得陪玩的所有商品（包括被逻辑删除的）
     * @Date 10.51 2022/8/20
     * @Author 魏才林
     * @Param [userId]
     **/
    @GetMapping("/goods/getPwGoods")
    public ResponseEntity getPwGoods(@RequestBody GoodsVo goodsVo) {
        //分页数，暂定10
        Integer pageSize = 10;

        PageBean<Goods> goodsPageBean = goodsService.getAllGoodsByUserId(goodsVo.getUserId(), goodsVo.getPageNum(), pageSize);
        return ResponseEntity.SUCCESS("获取陪玩商品列表成功（包括逻辑删除的）", goodsPageBean);
    }

    /**
     * 根据商品 id 获取单个商品
     *
     * @param id 商品id
     * @return com.woniu.woniu_bx.pojo.ResponseEntity
     * @Date 16:56 2022/8/31
     * @Author 魏才林
     **/
    @GetMapping("/goods/getGoodsById")
    public ResponseEntity getGoodsById(@NotNull Integer id) {
        return ResponseEntity.SUCCESS("ok", goodsService.getGoodsById(id));
    }


    /**
     * 根据类别 id 查询所有商品
     *
     * @param id 类别 id
     * @return 商品集合
     */
    @GetMapping("/goods/getByCategoryId")
    public ResponseEntity getByCategoryId(@NotNull Integer id) {
        List<Goods> goods = goodsService.getByCategoryId(id);
        //获取商品评分
        for(Goods g :goods){
            Goods goodsById = goodsService.getGoodsById(g.getId());
            BigDecimal goodsScore = goodsById.getGoodsScore();
            g.setGoodsScore(goodsScore);
        }
        GoodsCategory goodsCategory = goodsCategoryService.getById(id);
        GoodsList goodsList = new GoodsList();
        goodsList.setGoods(goods);
        goodsList.setGoodsCategory(goodsCategory);

        return ResponseEntity.SUCCESS("查询成功", goodsList);
    }
    /**
     * 根据类别 id 查询所有商品并通过销量排序
     *
     * @param goodsSortVo
     * @return 商品集合
     */
    @PostMapping("/goods/getByCategoryId/sort")
    public ResponseEntity saleNumSort(@RequestBody GoodsSortVo goodsSortVo) {
        ArrayList<Goods> goods = new ArrayList<>();
        if (goodsSortVo.getValue2() == 1) {
            goods = (ArrayList<Goods>) goodsService.getByCategoryId(goodsSortVo.getId());
        } else if (goodsSortVo.getValue2() == 2) {
            goods = (ArrayList<Goods>) goodsService.getByGenderAndCategoryId(goodsSortVo.getId(), "男");
        } else {
            goods = (ArrayList<Goods>) goodsService.getByGenderAndCategoryId(goodsSortVo.getId(), "女");
        }
        //获取商品评分
        for (Goods g : goods) {
            Goods goodsById = goodsService.getGoodsById(g.getId());
            BigDecimal goodsScore = goodsById.getGoodsScore();
            g.setGoodsScore(goodsScore);
        }

        if (goodsSortVo.getValue1() == 2) { //对商品进行排序(根据销量）
            Collections.sort(goods, new Comparator<Goods>() {
                @Override
                public int compare(Goods goods1, Goods goods2) {
                    //定义比较大小
                    if (goods1.getSaleNum() > goods2.getSaleNum()) {
                        return -1;
                    } else if (goods1.getSaleNum() == goods2.getSaleNum()) {
                        return 0;
                    } else {
                        return 1;
                    }
                }
            });
        } else if (goodsSortVo.getValue1() == 3) {//根据评分
            Collections.sort(goods, new Comparator<Goods>() {
                @Override
                public int compare(Goods goods1, Goods goods2) {
                    //定义比较大小
                    if (goods1.getGoodsScore().compareTo(goods2.getGoodsScore())==1) {
                        return -1;
                    } else if (goods1.getGoodsScore().compareTo(goods2.getGoodsScore())==0) {
                        return 0;
                    } else {
                        return 1;
                    }
                }
            });
        }
        //根据价格排序
        if (goodsSortVo.getValue3() == 2) {//升序
            Collections.sort(goods, new Comparator<Goods>() {
                @Override
                public int compare(Goods goods1, Goods goods2) {
                    //定义比较大小
                    if (goods1.getMoney().compareTo(goods2.getMoney())==1) {
                        return -1;
                    } else if (goods1.getMoney().compareTo(goods2.getMoney())==0) {
                        return 0;
                    } else {
                        return 1;
                    }
                }
            });
        }else if(goodsSortVo.getValue3() == 3){//降序
            Collections.sort(goods, new Comparator<Goods>() {
                @Override
                public int compare(Goods goods1, Goods goods2) {
                    return goods1.getMoney().compareTo(goods2.getMoney());
                }
            });
        }

        GoodsCategory goodsCategory = goodsCategoryService.getById(goodsSortVo.getId());
        GoodsList goodsList = new GoodsList();
        goodsList.setGoods(goods);
        goodsList.setGoodsCategory(goodsCategory);
        return ResponseEntity.SUCCESS("查询成功", goodsList);
    }
    /**
     * 后台：通过商品认证
     *
     * @param id 商品id
     * @return 操作成功响应
     */
    @GetMapping("/admin/goods/authPw/agree")
    @PreAuthorize("hasAnyAuthority('updown')")
    public ResponseEntity agreeAuthPw(@NotNull Integer id) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setAuthGoods("y");
        goodsService.updateByCondition(goods);
        return ResponseEntity.SUCCESS("通过商品审核成功", null);
    }


    /**
     * 后台：拒绝商品认证
     *
     * @param id 商品id
     * @return 操作成功响应
     */
    @GetMapping("/admin/goods/authPw/refuse")
    @PreAuthorize("hasAnyAuthority('updown')")
    public ResponseEntity refuseAuthPw(@NotNull Integer id) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setAuthGoods("n");
        goodsService.updateByCondition(goods);
        return ResponseEntity.SUCCESS("拒绝商品审核成功", null);
    }

    /**
     * 获取商品图片
     * @param id
     * @return
     */
    @GetMapping("/goods/getGoodsImages")
    public ResponseEntity<List<String>> getGoodsImages(@NotNull Integer id) {
        List<String> goodsImages = goodsService.getGoodsImagesById(id);
        return ResponseEntity.SUCCESS("ok", goodsImages);
    }

    /**
     * app展示商品详情
     * @param goods 商品id
     * @return
     */
    @PostMapping("/goods/showGoodsDetail")
    public ResponseEntity getGoodsShows(@RequestBody Goods goods){
        Goods pro = goodsService.getGoodsById(goods.getId());
        return ResponseEntity.SUCCESS("操作成功",pro);
    }

    //随机查询三条陪玩商品信息
    @GetMapping("/goods/random")
    public ResponseEntity<List<Goods>> findByRandom(){
        List<Goods> byRandom = goodsService.findByRandom();
        return ResponseEntity.SUCCESS("随机查询成功",byRandom);
    }


    /**
     * 根据发布商品的用户id查其发布的所有商品以及该用户信息
     * @param userId
     * @return
     */
    @GetMapping("/goods/getGoodsListByUserId")
    public ResponseEntity<List<Goods>> getGoodsListByUserId(String status, @NotNull Integer userId){
        List<Goods> goodsList = new ArrayList<>();
        if("all".equals(status)){
            goodsList = goodsService.getGoodsListByUserId(userId);
        }else {
            goodsList = goodsService.getGoodsListByUserIdAndStatus(userId,status);
        }
        return ResponseEntity.SUCCESS("查询成功",goodsList);
    }
}
